package problem;

import java.util.HashMap;
import java.util.Map;

/**
 * @author RunningShrimp
 * @date 2021/5/28  15:41
 * @see <a href=""></a>
 */
public class MapSum {
    private final Node root;

    public MapSum() {
        root = new Node();
    }

    public void insert(String key, int val) {
        Node cur = root;
        for (int i = 0; i < key.length(); i++) {
            char c = key.charAt(i);
            if (cur.next.get(c) == null) {
                cur.next.put(c, new Node());
                break;
            }
            cur = cur.next.get(c);
        }
        cur.num = val;
    }

    public int sum(String prefix) {
        Node cur = root;
        int sum = 0;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (cur.next.get(c) == null) {
                return 0;
            }
            cur = cur.next.get(c);
        }

        return sum(cur);
    }

    private int sum(Node node) {
        if (node.next.size() == 0) {
            return node.num;
        }
        int res = node.num;
        for (Character c : node.next.keySet()) {
            res += sum(node.next.get(c));
        }
        return res;
    }

    private class Node {
        private int num;
        private final Map<Character, Node> next;

        public Node(int num) {
            this.num = num;
            next = new HashMap<>();
        }

        public Node() {
            this(0);
        }
    }
}
